/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * UnifiedForm.java
 *
 * Created on Nov 6, 2009, 2:07:51 PM
 */

package gui;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.awt.event.KeyEvent;
import java.util.Timer;
import java.util.TimerTask;
/**
 *
 * @author hrushi
 */
public class UnifiedForm extends javax.swing.JFrame {

    public static int SEQ_CNT = 1;
    public static int SPORT;
    public static int DPORT;
    public static int MAXBUF = 65535;
    public static String[][] recv_seq;
    public static int CURR_RCV = 0;
    public static int MAX_RCV = 100;
    public static boolean SERV_THR_RUN = false;
    //public static String CONFIGFILEPATH = "./../../config/hosts"; // when running from netbeans
    public static String CONFIGFILEPATH = "./../../../config/hosts";  // when running from command line
    
    Timer timer;

    /** Creates new form UnifiedForm */
    public UnifiedForm() {
        initComponents();
        recv_seq = new String[MAX_RCV][2];
        listModel = new DefaultListModel();
        listM = new DefaultListModel();
        listModel1 = new DefaultListModel();
        NamesList.setModel(listModel);
        GroupsList.setModel(listModel1);
        buttonGroup1.add(jRadioButton1);
        buttonGroup1.add(jRadioButton2);
        jRadioButton1.doClick();
        
        /* These two lines of code refreshes the form every 10000 ms so that the form is synchronized with the hosts file written by the sniffer */
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() { public void run() { initializeForm(); } } ,0, 10000);
       
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        NamesList = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        GroupsList = new javax.swing.JList();
        jLabel2 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jTextField6 = new javax.swing.JTextField();
        jTextField7 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jTextField2 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jTextField5 = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jPanel6 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();
        SendButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("MyMANET_gui"); // NOI18N
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                winActivated(evt);
            }
        });

        jScrollPane1.setViewportView(jTextPane1);

        jPanel4.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        NamesList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Demo" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        NamesList.setDragEnabled(true);
        NamesList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                ListSelected(evt);
            }
        });
        jScrollPane3.setViewportView(NamesList);

        jLabel1.setText("Buddies");

        GroupsList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Demo" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        GroupsList.setDragEnabled(true);
        GroupsList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                GroupsListListSelected(evt);
            }
        });
        jScrollPane4.setViewportView(GroupsList);

        jLabel2.setText("Groups");

        jButton2.setText("Add Group");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addContainerGap(114, Short.MAX_VALUE))
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(40, Short.MAX_VALUE))
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addContainerGap(119, Short.MAX_VALUE))
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(jButton2))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(40, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(16, Short.MAX_VALUE))
        );

        jPanel5.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel3.setFont(new java.awt.Font("Corbel", 1, 18));
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText("MyMANET");
        jLabel3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jTextField6.setText("4440");

        jTextField7.setText("4440");

        jButton1.setText("Start");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(63, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jTextField7, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextField6, javax.swing.GroupLayout.Alignment.LEADING))
                .addGap(94, 94, 94))
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(83, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap(14, Short.MAX_VALUE))
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jTextField2.setEditable(false);
        jTextField2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField2ActionPerformed(evt);
            }
        });

        jLabel5.setText("IPv4");

        jTextField4.setEditable(false);
        jTextField4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField4ActionPerformed(evt);
            }
        });

        jLabel7.setText("MAC");

        jTextField5.setEditable(false);

        jLabel8.setText("Name");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE)
                    .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jTextField5, javax.swing.GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE)
                    .addComponent(jTextField4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jRadioButton1.setText("Chat mode");

        jRadioButton2.setText("Group mode");
        jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jRadioButton1)
                    .addComponent(jRadioButton2))
                .addContainerGap(67, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addComponent(jRadioButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jRadioButton2)
                .addContainerGap(21, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addGap(51, 51, 51)
                        .addComponent(jLabel3))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(42, Short.MAX_VALUE))
        );

        jPanel6.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel6.setText("MAC");

        jTextField3.setEditable(false);
        jTextField3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField3ActionPerformed(evt);
            }
        });

        jLabel4.setText("IPv4");

        jTextField1.setEditable(false);

        jTextArea2.setColumns(20);
        jTextArea2.setRows(5);
        jTextArea2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                keyPressDetected(evt);
            }
        });
        jScrollPane2.setViewportView(jTextArea2);

        SendButton.setFont(new java.awt.Font("Corbel", 1, 14));
        SendButton.setText("SEND");
        SendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SendButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jTextField1)
                    .addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 117, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 470, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(SendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 54, Short.MAX_VALUE)
                    .addComponent(SendButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel6Layout.createSequentialGroup()
                        .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel6Layout.createSequentialGroup()
                                .addGap(16, 16, 16)
                                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel6Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jTextField1, 0, 0, Short.MAX_VALUE)))))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 357, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(38, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(35, 35, 35))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /* This function is executed when the form is loaded for the first time and subsequently when it is refreshed by the timer */
    
    private void initializeForm() {
        String[] strArr1;
        String[] strSplit1;
        FileHandler buddiesR = new FileHandler (CONFIGFILEPATH);

        /* Initialize the lists and the text boxes */
        listModel.clear();
        //listModel1.clear();
        jTextField1.setText("");
        jTextField2.setText("");
        jTextField3.setText("");
        jTextField4.setText("");
        jTextField5.setText("");
        //jTextArea2.setText("");
        
        System.out.println(System.getProperty("user.dir"));

        /* Open the hosts file in the config directory of mymanet folder.. it is written by the sniffer and is present as long
         * as the network is active. It contains the list of hosts currently active in the network
         * 'hosts' file is deleted when stop.sh is run to stop the network */
        /* The openFile function returns true if the file is successfully opened, else it return false. 
         * Parameter 0 is used when the file is opened for reading */
        if (buddiesR.openFile(0)) {
            strArr1 = buddiesR.readIntoArray(); // The file is read into an array of strings
            buddiesR.closeFile();

            try
            {
                listModel.clear();

                /* Add each host from the 'hosts' file into the buddies list of the form */
                for (int i=0; i<strArr1.length; i++) {

                    strSplit1 = strArr1[i].split(" ");
                    listModel.addElement(strSplit1[0]);

                    if (strSplit1[2].trim().equals(strSplit1[3].trim())) {
                        jTextField2.setText(strSplit1[1]);
                        jTextField4.setText(strSplit1[2]);
                        jTextField5.setText(strSplit1[0]);
                    }
                }

            } catch (java.lang.NullPointerException e)
            {
                System.out.println("Nullpointerexc in initialize form");
            } catch (ArrayIndexOutOfBoundsException exc) {
                System.out.println("Arrayoutofbounds in initialize form");
            }

            /* Select the first item of the list as default */
            NamesList.setSelectedIndex(0);
        }
        else {
            
            /* If the file is not opened succesfully, it is assumed that the failure to open the 'hosts' file is a 
             * result of the network not being active. Hence, it is concluded that the network is inactive and the
             * relevant error message is shown in th relevant text boxes. */
            
            listModel.clear();
            listModel1.clear();
            listModel.addElement("Network inactive");
            //listModel1.addElement("Network inactive");
            jTextField1.setText("Network inactive");
            jTextField2.setText("Network inactive");
            jTextField3.setText("Network inactive");
            jTextField4.setText("Network inactive");
            jTextField5.setText("Network inactive");
            //jTextArea2.setText("Network inactive");
        }
            
    }

    private void winActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_winActivated
        // TODO add your handling code here:
        initializeForm();
    }//GEN-LAST:event_winActivated

    public String getMyName() {
        return jTextField5.getText();
    }
            
    
    private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed
        // TODO add your handling code here:

    }//GEN-LAST:event_jTextField3ActionPerformed

    private void ListSelected(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_ListSelected
        // TODO add your handling code here:
        String[] strArr1;
        String[] strSplit1;
        FileHandler buddiesR = new FileHandler (CONFIGFILEPATH);
        String selValue;
        
        /* Refer documentation from the initializeform function */
        if (buddiesR.openFile(0)) {
            strArr1 = buddiesR.readIntoArray();
            buddiesR.closeFile();

            try {
                selValue=NamesList.getSelectedValue().toString().trim();  // get the selected value from the list

                /* Search for the selected value from the list into the hosts file to obtain the relevant IP and MAC 
                 * addressed to be displayed in their relevant text boxes on the form */
                for (int i=0; i<strArr1.length; i++) {

                    strSplit1 = strArr1[i].split(" ");  // split each line from the hosts file into multiple strings

                    /* Update the text boxes when the match is found */
                    if (strSplit1[0].trim().equals(selValue.trim())) {
                        jTextField3.setText(strSplit1[2]);
                        jTextField1.setText(strSplit1[1]);
                    }
                }


            }catch (java.lang.NullPointerException ex) {
                System.out.println("Inside this place");
               // ex.printStackTrace();
            } catch (ArrayIndexOutOfBoundsException exc) {
                System.out.println("Arrayoutofbounds in list selected");
            }
        }
    }//GEN-LAST:event_ListSelected

    private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField4ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField4ActionPerformed

    /* This function decides the source and destination names and IP addresses and feeds them to the sendMessage
     * function as arguments. If it is chat mode, then the source and destination names and IP addresses are obtained
     * from the relevant text boxes. If is is group mode, then the message has to be sent to all members (names) of the
     * group. The member names are extracted and a separate message is sent to each one of them */
    private void processSend() {
        if (SERV_THR_RUN==true) {
            if (jRadioButton2.isSelected()) {   //When it is group chat mode
                FileHandler buddiesR = new FileHandler (CONFIGFILEPATH);
                
                /* Get the selected string from the groups list. It contains the names of the group members 
                 * separated by space " " */
                String temp = GroupsList.getSelectedValue().toString();
                String[] temp1, strArr1, strSplit1;
                
                /* Refer documentation in initializeform function */
                if (buddiesR.openFile(0)) {
                    strArr1 = buddiesR.readIntoArray();
                    buddiesR.closeFile();

                    temp1 = temp.split(" "); // Split the group member names list into multiple strings each having one name into array temp1
                    /* For each of the name, search for its IP into the hosts file and then feed the data to
                     * sendMessage function */
                    for (int i=0; i<temp1.length; i++) {

                        String destIP="", destName="";

                        for (int j=0; j<strArr1.length;j++) {
                            strSplit1 = strArr1[j].split(" ");
                            if (strSplit1[0].trim().equals(temp1[i].trim())) {
                                destIP = strSplit1[1];
                                destName = strSplit1[0];
                                break;
                            }
                        }
    //                    System.out.println(destName + " " + destIP);
                        sendMessage(jTextField2.getText(), jTextField5.getText(), destIP, destName, SEQ_CNT, jTextArea2.getText().length(), jTextArea2.getText(), 0);
                        SEQ_CNT++;
                    }
                    modifyMainTextArea("Me >> " + jTextArea2.getText(), "", 0, 0);
                    jTextArea2.setText("");
                }
                 
            } else if (jRadioButton1.isSelected()) {
                /* Get data from the relevant text boxes and feed to the sendMessage function when it is chat mode */
                String[] strArr1;
                String destIP=jTextField1.getText(), destName=NamesList.getSelectedValue().toString();
                sendMessage(jTextField2.getText(), jTextField5.getText(), destIP, destName, SEQ_CNT, jTextArea2.getText().length(), jTextArea2.getText(), 0);
                SEQ_CNT++;
                modifyMainTextArea("Me >> " + jTextArea2.getText(), "", 0, 0);
                jTextArea2.setText("");
            }
        }        
    }
    
    private void SendButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SendButtonActionPerformed
        // TODO add your handling code here:
        processSend();

    }//GEN-LAST:event_SendButtonActionPerformed

    private void sendMessage(String src_ip, String src_name, String dest_ip, String dest_name, int seq_num, int payload_length, String payload, int type) {
        try {
            char[] destIP, destName, srcIP, srcName;
            /* String to character array conversions required */
            srcIP = src_ip.toCharArray();
            srcName = src_name.toCharArray();
            destIP = dest_ip.toCharArray();
            destName = dest_name.toCharArray();

            /* Create a chatmessage object and write it onto the output stream using datagram sockets */
            ChatMessage chat = new ChatMessage(srcIP, srcName, destIP, destName, seq_num, payload_length, payload, type);
            DatagramSocket socket = new DatagramSocket ();
            InetAddress ipAdd = InetAddress.getByName(String.valueOf(destIP));
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            ObjectOutputStream oStream = new ObjectOutputStream(byteStream);
            oStream.writeObject(chat);
            oStream.flush();
            byte [] buf = byteStream.toByteArray();
            //System.out.println("Dest: " + gui.UnifiedForm.SPORT);
            DatagramPacket packet = new DatagramPacket(buf, buf.length, ipAdd, DPORT);
            socket.send(packet);

        } catch (java.net.SocketException ex) {
            System.out.println ("In socket exc sendmessage");
            //ex.printStackTrace();
        } catch (java.net.UnknownHostException ex) {
            System.out.println ("In unk host exc sendmessage");
            //ex.printStackTrace();
        } catch (java.io.IOException ex) {
            System.out.println ("In IO exc sendmessage");
            //ex.printStackTrace();
        }
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        if (jButton1.getText().trim().equals("Start")) {

            SPORT = Integer.parseInt(jTextField6.getText());
            DPORT = Integer.parseInt(jTextField7.getText());
            //System.out.println(DPORT);

            if (svrThread==null)
                (svrThread = new ServerThread(this)).start();

            SERV_THR_RUN = true;
            jButton1.setText("Stop");
        }
        else {
            SERV_THR_RUN = false;
            jButton1.setText("Start");
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField2ActionPerformed

    private void GroupsListListSelected(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_GroupsListListSelected
        // TODO add your handling code here:
    }//GEN-LAST:event_GroupsListListSelected

    /* When the group chat button is selected select the first item of the groups list as default */
    private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton2ActionPerformed
        // TODO add your handling code here:
        GroupsList.setSelectedIndex(0);
    }//GEN-LAST:event_jRadioButton2ActionPerformed

    /* This function is called when the enter key is pressed onto jTextArea2 */
private void keyPressDetected(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_keyPressDetected
// TODO add your handling code here:
    if (evt.getKeyChar()==KeyEvent.VK_ENTER) {
        processSend();
    }
}//GEN-LAST:event_keyPressDetected

/* This function is used to create groups. The user selects multiple items from the buddies list and then presses the
 * 'add group' button. When this happens a new entry is added to the groups list which contains all the names selected;
 * names are separated by space " ". The names are taken from the selected values of the buddies list */

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
            String selValue=NamesList.getSelectedValue().toString().trim();
            int[] selIndices = NamesList.getSelectedIndices();
            
            String text = "";
            for (int i=0; i<selIndices.length; i++) {
                if (i!=(selIndices.length-1))
                    text = text + listModel.elementAt(selIndices[i]).toString() + " ";
                else
                    text = text + listModel.elementAt(selIndices[i]).toString();
            }
            listModel1.addElement(text);
}//GEN-LAST:event_jButton2ActionPerformed

/*
 * This function is used to modify the main textArea where the user can see the chat messages */

    public void modifyMainTextArea(String str1, String str2, int mode, int clearFlag) {
        if (clearFlag==1) {
            jTextPane1.setText("");
        }
        if (!str2.equals("")) {
            if (listM.getSize()>5) listM.clear();
            listM.add(0, str2);
        }
        jTextPane1.setText(jTextPane1.getText() + str1 + "\n");
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new UnifiedForm().setVisible(true);
            }
        });

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList GroupsList;
    private javax.swing.JList NamesList;
    private javax.swing.JButton SendButton;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    private javax.swing.JTextField jTextField7;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration//GEN-END:variables
    private DefaultListModel listModel;
    private DefaultListModel listM;
    private DefaultListModel listModel1;
    private ServerThread svrThread;
}
